package com.base.interview.devtest.service;

import com.base.interview.devtest.entity.PostEntity;
import com.base.interview.devtest.model.dto.PostDTO;
import com.base.interview.devtest.model.vo.PostVO;
import com.base.interview.devtest.repository.PostRepository;
import com.base.interview.devtest.util.DateUtil;
import com.base.interview.devtest.util.SessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PostService implements IPostService {
    @Autowired
    private PostRepository postRepository;
    @Autowired
    private IUserService userService;

    @Override
    public PostVO createNewPost(PostDTO postDTO) {
        PostEntity postEntity = new PostEntity();
        postEntity.setCreateDt(new Date());
        postEntity.setTextContent(postDTO.getContent());
        postEntity.setUserId(SessionManager.getThreadUser());
        postRepository.save(postEntity);

        PostVO postVO = new PostVO();
        postVO.setContent(postDTO.getContent());
        postVO.setPostDate(DateUtil.format(postEntity.getCreateDt()));
        postVO.setPostId(postEntity.getId());
        postVO.setUserName(userService.getUserName(postEntity.getUserId()));
        postVO.setUserId(postEntity.getUserId());
        return postVO;
    }

    @Override
    public List<PostVO> listAllPosts() {
        PageRequest pageRequest = PageRequest.of(0, 50, Sort.by(Sort.Direction.DESC, "id"));
        Page<PostEntity> postEntities = postRepository.findAll(pageRequest);
        return postEntities.stream().map(postEntity -> convert(postEntity)).collect(Collectors.toList());
    }

    @Override
    public List<PostVO> listPosts(Long userId) {
        List<PostEntity> postEntities = postRepository.getByUserId(userId);
        return postEntities.stream().map(postEntity -> convert(postEntity)).collect(Collectors.toList());
    }

    private PostVO convert(PostEntity postEntity) {
        PostVO postVO = new PostVO();
        postVO.setUserName(userService.getUserName(postEntity.getUserId()));
        postVO.setPostId(postEntity.getId());
        postVO.setPostDate(DateUtil.format(postEntity.getCreateDt()));
        postVO.setContent(postEntity.getTextContent());
        postVO.setUserId(postEntity.getUserId());
        return postVO;
    }

}
